from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
import datetime
import json
import redis

r = redis.Redis('localhost', port=6379, db=1, decode_responses=True)

# 订单链接
order_url = 'https://item.jd.com/100002019843.html'
# 选择银行
pay_name = '中国光大银行'


class Jd(object):
    # 初始化参数
    def __init__(self):
        options = webdriver.ChromeOptions()
        # if r.get('jd') is not None:
        #     options.add_argument('--headless')
        self.browser = webdriver.Chrome(options=options)
        self.wait = WebDriverWait(self.browser, 1)

    # cookies登陆
    def login(self):
        print('cookies免扫登陆')
        if r.get('jd') is None:
            raise 'redis cookies not find'

        listCookies = json.loads(r.get('jd'))

        self.browser.get('https://passport.jd.com/new/login.aspx')
        self.browser.delete_all_cookies()

        for cookie in listCookies:
            self.browser.add_cookie(cookie)

    # 扫码登陆
    def scan_login(self):
        print('扫码登陆')
        self.browser.get('https://passport.jd.com/new/login.aspx')
        while True:
            try:
                self.wait.until(
                    EC.text_to_be_present_in_element((
                        By.CSS_SELECTOR,
                        '#shortcut > div > ul.fr > li.shortcut_btn.fore2 > div > a'
                    ), '我的订单'))
                if r.get('jd') is None:
                    r.set('jd', json.dumps(self.browser.get_cookies()))
                    break
            except TimeoutException:
                print('继续等待扫码登陆')

    # 抢购订单
    def pay_shop(self):
        # 打开订单
        self.browser.get(order_url)

        # 立即抢购
        while True:
            try:
                self.wait.until(
                    EC.text_to_be_present_in_element(
                        (By.CSS_SELECTOR, '#btn-reservation'), '立即抢购'))
                # 立即抢购
                self.wait.until(
                    EC.presence_of_element_located((
                        By.CSS_SELECTOR,
                        '#btn-reservation'
                    ))).click()
            except (NoSuchElementException, TimeoutException):
                self.browser.refresh()
                print('没有找到,尝试刷新页面.')

        # 提交订单
        self.wait.until(
            EC.presence_of_element_located((
                By.CSS_SELECTOR,
                '#app > div > div.container > div > div.order-summary > div.trade-foot > div.checkout-floatbar > div > div > div > button'
            ))).click()

        # 选择银行
        self.wait.until(
            EC.presence_of_element_located(
                (By.XPATH, '//strong[text()="{}"]'.format(pay_name)))).click()

        # 输入支付密码
        self.wait.until(
            EC.presence_of_element_located((
                By.CSS_SELECTOR,
                '#payChannelListId > div:nth-child(5) > div > div.pv-line.pv-line-shortPwd > span > input:nth-child(1)'
            ))).send_keys('472323')

        # 确认支付
        self.wait.until(
            EC.presence_of_element_located((
                By.CSS_SELECTOR,
                '#payChannelListId > div:nth-child(5) > div > div:nth-child(6) > a'
            ))).click()

        self.wait.until(
            EC.text_to_be_present_in_element((
                By.CSS_SELECTOR,
                '#resultArea > div.porm-result-area.clearfix > div.pay-result-infor-box > div.result-infor-con > p:nth-child(2)'
            ), '购买成功'))

        print('完成支付成功')

    def run(self):
        if r.get('jd') is None:
            self.scan_login()
        else:
            self.login()

        start_time = datetime.datetime(2019, 2, 19, 9, 59, 59)
        print('任务时间: {}'.format(start_time.strftime('%Y-%m-%d %H:%M:%S')))

        while True:
            if datetime.datetime.today() >= start_time:
                print('时间到了')
                self.pay_shop()
                break


# 运行
Jd().run()
